package com.cheng.controller;

import com.cheng.pojo.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class MyController {

    @RequestMapping(value = "/doMain")
    public String doMain(Model model) {
        model.addAttribute("name", "springmvc");
        return "main";
    }

    @GetMapping(value = "/login")
    public ModelAndView login(@RequestParam("account") String account, String password) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("account", account);
        modelAndView.addObject("password", password);

        modelAndView.setViewName("success");
        return modelAndView;
    }

    @RequestMapping(value = "/loginTakeObject")
    public ModelAndView loginTakeObject(User user) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("account", user.getAccount());
        modelAndView.addObject("password", user.getPassword());

        modelAndView.setViewName("success");
        return modelAndView;
    }

    @RequestMapping(value = "/getJsonByReturnVoid")
    public void getJsonByReturnVoid(HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        User user = new User();
        user.setAccount("12312312");
        user.setPassword("admin123");

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        out.print(json);
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/getJsonByReturnObject")
    @ResponseBody
    public List<User> getJsonByReturnObject() {
        List<User> list = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            User user = new User();
            user.setAccount("1000" + i);
            user.setPassword("qwe@qw" + i + 1);
            list.add(user);
        }

        return list;
    }


}
